import os
from time import sleep
import paho.mqtt.client as paho
import logging
import json
#引入线程
import threading
import time


kt_list = [

]

T_TOPIC = "zigbee2mqtt/空调设备/行政楼面板/+"
RPC_TOPIC = "zigbee2mqtt/空调设备/行政楼面板/+/rpc"

class MqttClient:
    def __init__(self, config: dict) -> None:
        global _log
        self._config = config
        self.ip = config["host"]
        self.port = config["port"]
        _log = logging.getLogger('mqtt')
        self._client = paho.Client(protocol=paho.MQTTv311)
        self._client.on_connect = lambda _, __, ____, rc: self.on_connect_cb(rc)
        self._client.on_message = self._on_message_cb
        self.kt_topic_devces = {}
        self.rpc_msg = {}

    def on_connect_cb(self, rc: int):
        print("conn okkkkk")
        _log.info("Connected mqtt broker %s with result: %d", self._config["host"], rc)

    def send_msg(self,  msg: dict, qos:int = 0,topic: str = T_TOPIC):
        payload = json.dumps(msg)
        print(f"mqtt发送数据topic:{topic},payload:{payload}")
        _log.debug("topic:",topic,"payload:",payload)
        self._client.publish(topic, payload, qos)

    def start(self):
        self._client.username_pw_set(username="juji1234", password="juji1234")
        self._client.connect(self._config["host"], self._config["port"], 60)
        self._client.loop_start()
        #订阅topic
        self._client.subscribe(T_TOPIC)
        self._client.subscribe(RPC_TOPIC)
        while True:
            print("轮询")
            #轮询topic
            self._pre_send_msg()
            sleep(10)
            pass
    
    def stop(self):
        self._client.loop_stop()

    def deal_rpc_msg(self,msg):
        key = json.loads(msg.payload.decode("utf-8"))
        if msg.topic.replace("/rpc","") not in self.rpc_msg:
            self.rpc_msg[msg.topic.replace("/rpc","")] = {}
        #将更新到self.rpc_msg
        for k in key:
            try:
                self.rpc_msg[msg.topic.replace("/rpc","")][k] = int(key[k])
            except:
                self.rpc_msg[msg.topic.replace("/rpc","")][k] = key[k]

        if "SetAirVolume" in key:
            try:
                value = int(key["SetAirVolume"])
            except:
                value = key["SetAirVolume"]
            if 0 < value <= 30:
                self.send_msg(msg={"WindSpeed":"low"},topic=msg.topic.replace("/rpc","/set"))
            elif value == 0:
                self.send_msg(msg={"state":"OFF"},topic=msg.topic.replace("/rpc","/set"))
            elif 30 < value <= 60:
                self.send_msg(msg={"WindSpeed":"middle"},topic=msg.topic.replace("/rpc","/set"))
            elif 60 < value <= 100:
                self.send_msg(msg={"WindSpeed":"high"},topic=msg.topic.replace("/rpc","/set"))
        elif "SetTemperature" in key:
            try:
                value = int(key["SetTemperature"])
            except:
                value = key["SetTemperature"]
            if 16 <= value <= 30:
                self.send_msg(msg={"SetCurrentTem":key["SetTemperature"]},topic=msg.topic.replace("/rpc","/set"))

    def _pro_sub_topic(self,topiclist:list):
        for topic in topiclist:
            self._client.subscribe(topic)
            print(topic)

    def save_msg(self,msg,payload):
        #处理payload
        new_payload = {}
        if "state" in payload:
            new_payload["state"] = payload["state"]
        if "SetCurrentTem" in payload:
            new_payload["SetTemperature"] = payload["SetCurrentTem"]
        if "WindSpeed" in payload:
            if payload["WindSpeed"] == "low":
                if msg.topic in self.rpc_msg:
                    if "SetAirVolume" in self.rpc_msg[msg.topic]:
                        if 0 < self.rpc_msg[msg.topic]["SetAirVolume"] <= 30:
                            new_payload["SetAirVolume"] = self.rpc_msg[msg.topic]["SetAirVolume"]
                        else:
                            new_payload["SetAirVolume"] = 30
                    else:
                        new_payload["SetAirVolume"] = 30
                else:
                    new_payload["SetAirVolume"] = 30
            elif payload["WindSpeed"] == "middle":
                if msg.topic in self.rpc_msg:
                    if "SetAirVolume" in self.rpc_msg[msg.topic]:
                        if 30 < self.rpc_msg[msg.topic]["SetAirVolume"] <= 60:
                            new_payload["SetAirVolume"] = self.rpc_msg[msg.topic]["SetAirVolume"]
                        else:
                            new_payload["SetAirVolume"] = 60
                    else:
                        new_payload["SetAirVolume"] = 60
                else:
                    new_payload["SetAirVolume"] = 60
            elif payload["WindSpeed"] == "high":
                if msg.topic in self.rpc_msg:
                    if "SetAirVolume" in self.rpc_msg[msg.topic]:
                        if 60 < self.rpc_msg[msg.topic]["SetAirVolume"] <= 100:
                            new_payload["SetAirVolume"] = self.rpc_msg[msg.topic]["SetAirVolume"]
                        else:
                            new_payload["SetAirVolume"] = 100
                    else:
                        new_payload["SetAirVolume"] = 100
                else:
                    new_payload["SetAirVolume"] = 100

        #储存三个值，topic，newpayload，time
        if T_TOPIC.replace("+","") in msg.topic and "/set" not in msg.topic:
            if msg.topic not in self.kt_topic_devces:
                self.kt_topic_devces[msg.topic] = {}
                self.kt_topic_devces[msg.topic]["payload"] = new_payload
                self.kt_topic_devces[msg.topic]["time"] = time.time()
            else:
                self.kt_topic_devces[msg.topic]["payload"] = new_payload
                self.kt_topic_devces[msg.topic]["time"] = time.time()

    def _on_message_cb(self,client, userdata, msg):
        # print(msg.topic+" "+str(msg.payload))
        payload = msg.payload.decode("utf-8")
        #转化为字典
        payload = json.loads(payload)
        if "rpc" in msg.topic:
            self.deal_rpc_msg(msg)
        else:
            #保存msg
            self.save_msg(msg,payload)
        
    def _pre_send_msg(self):
        #遍历self.kt_topic_devces，如果有消息不超过5分钟，就发送
        for k in self.kt_topic_devces:
            if time.time() - self.kt_topic_devces[k]["time"] < 300:
                self.send_msg(msg = self.kt_topic_devces[k]["payload"], topic=k.replace("zigbee2mqtt/",""))
        pass

if __name__ == "__main__":
    # 1. 创建一个mqtt客户端
    config = {}
    config["host"] = "127.0.0.1"
    config["port"] = 1883

    mqc = MqttClient(config)
    mqc.start()

